<?php declare(strict_types=1);
/**
 * @author      xianganyall <xianganyall@gmail.com>
 * @copyright   2023-2025 owner
 **/

namespace Srv\Libs\Plugins\Protos;

use Google\Protobuf\Struct;
use Google\Protobuf\Value;

class ProtoStruct
{
    /**
     * @param array $structList
     * @param bool $strict
     * @param bool $isFail
     * @return Struct
     * genStruct
     */
    public static function genStruct(array $structList, bool $strict = false, bool &$isFail = false):Struct
    {
        $isFail                 = false;
        $Struct                 = new Struct();
        if(count($structList) < 1){
            $isFail             = true;
            return $Struct;
        }
        $fieldList              = [];
        foreach ($structList as $structKey => $structVal){
            if(!is_string($structKey)){
                if(!$strict){
                    $isFail     = true;
                    return $Struct;
                }
                $structKey      = '_'.$structKey;
            }
            $isFailItem         = false;
            $ValueItem          = ProtoValue::genVarValue($structVal, $strict, $isFailItem);
            if($isFailItem){
                if(!$strict){
                    $isFail     = true;
                    return $Struct;
                }else{
                    continue;
                }
            }
            $fieldList[$structKey] = $ValueItem;
        }
        $Struct->setFields($fieldList);
        return $Struct;
    }

    /**
     * @param array $structList
     * @param bool $strict
     * @param bool $isFail
     * @return Value
     * genStructValue
     */
    public static function genStructValue(array $structList, bool $strict = false, bool &$isFail = false):Value
    {
        $isFail                 = false;
        $ValueStruct            = new Value();
        $Struct                 = new Struct();
        $ValueStruct->setStructValue($Struct);
        if(count($structList) < 1){
            $isFail             = true;
            return $ValueStruct;
        }
        $Struct                 = self::genStruct($structList, $strict, $isFail);
        if($isFail) return $ValueStruct;
        $ValueStruct->setStructValue($Struct);
        return $ValueStruct;
    }
}